package com.qf.controller;


import com.aliyuncs.exceptions.ClientException;
import com.qf.entity.DTO.UserDTO;
import com.qf.entity.User;
import com.qf.service.IUserService;
import com.qf.utils.Constant;
import com.qf.utils.FileUpUtil;
import com.qf.utils.SmsUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;


/**
 * @description:
 * @author: ssq
 * @time: 2020/8/10 16:40
 */

@RestController
@RequestMapping("/user")
public class UserLoginController {

    @Autowired
    private IUserService iUserService;
    @Autowired
    private RedisTemplate redisTemplate;

    //获取验证码
    @RequestMapping("/codeCheck/{uPhone}")
    public String getcode(@PathVariable("uPhone") String uPhone) throws ClientException {

        //产生6位的验证码
        String code = SmsUtil.createCode();
        //发送信息
        SmsUtil.sendSms(uPhone, code);
        //按照手机号码储存验证码
        redisTemplate.opsForValue().set(uPhone, code);
        //返回前端
        return "1";
    }

    @RequestMapping("/login/{uPhone}/{code}")
    public String login(@PathVariable("uPhone") String uPhone, @PathVariable("code") String code, HttpSession session) {

        //验证手机号码是否为空
        if (null == uPhone || "".equals(uPhone)) {
            return "0";
        }
        //根据手机号码-->获取session中的验证码
        String codeRedis = (String) redisTemplate.opsForValue().get(uPhone);
        //比较验证码是否正确
        if (code.equals(codeRedis)) {
            return "1";
        }
        return "0";
    }

    @RequestMapping("/addUser")
    public UserDTO add(User user) {
        UserDTO userDTO = new UserDTO();
        iUserService.addUser(user);
        userDTO.setUser(user);
        System.out.println(user.getuId());
        userDTO = iUserService.findUser(user.getuId());
        return userDTO;
    }

    @RequestMapping(value = {"/upload"}, method = RequestMethod.POST)
    public String uploadFile(MultipartFile file, HttpServletRequest request) {
        String path = FileUpUtil.fileUp(request, file, Constant.upload_path);
        return path;
    }
}


